﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Xml.Linq;
using EasyOAuth.Core.OAuth;
using EasyOAuth.Core.Web;

namespace MingHui.ShopExpress.Manage.API
{
    /// <summary>
    /// 用户授权验证
    /// </summary>
    public class OAuthAttribute : Attribute, IAuthorizationFilter
    {
        /// <summary>
        /// 授权验证 
        /// </summary>
        /// <param name="context"></param>
        public void OnAuthorization(AuthorizationFilterContext context)
        {

            //不授权
            if (context.Filters.Contains(new OAuthIgnoreAttribute()))
            {
                return;
            }

            var cookies = context.HttpContext.Request.Headers;

            var authorization = cookies["Authorization"];

            var accessToken = new AccessTokenBuilder();

            if (string.IsNullOrWhiteSpace(authorization))
            {
                context.Result = new JsonResult(new ApiResult() { Code = 402, Msg = "授权无效token为空" });
                return;
            }

            if (accessToken.Validate(authorization) == false)
            {
                context.Result = new JsonResult(new ApiResult() { Code = 401, Msg = "授权无效" });
                return;
            }
        }


    }

    /// <summary>
    /// 忽略用户授权验证
    /// </summary>
    public class OAuthIgnoreAttribute : Attribute, IFilterMetadata
    {

    }

}
